﻿using System;
using System.Web.Mvc;
using System.Linq;
using System.Collections.Generic;

namespace iHouse.Web.Infrastructure
{
    public class JsonExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        #region IExceptionFilter Member

        public void OnException(ExceptionContext filterContext)
        {
            string errorMassage = filterContext.Exception.Message;
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                foreach (var state in filterContext.Controller.ViewData.ModelState)
                {
                    if (state.Value.Errors.Count > 0)
                    {
                        errorMassage = state.Value.Errors[0].ErrorMessage;
                        break;
                    }
                }
            }

            dynamic data = new Dictionary<string, object>();
            data["success"] = false;
            data["message"] = errorMassage;

            filterContext.Result = new JsonResult() { Data = data };
            filterContext.ExceptionHandled = true;
        }

        #endregion
    }
}
